package com.css.fxfzfxqh.modules.seismicHazardData.repository.impl;

import com.css.fxfzfxqh.modules.seismicHazardData.entity.ArModelEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.entity.SeismicPbeEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.entity.SettingInfluenceFliedEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.entity.SettingSeismicProcessEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.param.arModel.ArModelPageParam;
import com.css.fxfzfxqh.modules.seismicHazardData.repository.SeismicImpactFieldRepository;
import com.css.fxfzfxqh.modules.seismicHazardData.vo.InfluencefliedVo;
import com.css.fxfzfxqh.modules.seismicHazardData.vo.ModelPageVo;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class SeismicImpactFieldRepositoryImpl implements SeismicImpactFieldRepository {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SysAreaService sysAreaService;

    @Autowired
    private SysAreaService areaService;

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public void saveArModel(ArModelEntity entity) {
        jdbcTemplate.update("insert into fxqh_attenuation_relationship_model  (id,model_name,province,city,long_ratio1,long_ratio2,long_ratio3,long_ratio4,long_symbol,short_ratio1,short_ratio2,short_ratio3,short_ratio4,short_symbol,formula_ratio1,formula_ratio2,scale,is_default,create_user_id,create_user_name,create_time,org_id,org_name,del_flag,type) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                entity.getId(), entity.getModelName(), entity.getProvince(), entity.getCity(), entity.getLongRatio1(), entity.getLongRatio2(), entity.getLongRatio3(), entity.getLongRatio4(), entity.getLongSymbol(), entity.getShortRatio1(), entity.getShortRatio2(), entity.getShortRatio3(), entity.getShortRatio4(), entity.getShortSymbol(), entity.getFormulaRatio1(), entity.getFormulaRatio2(), entity.getScale(), entity.getIsDefault(), entity.getCreateUserId(), entity.getCreateUserName(), entity.getCreateTime(), entity.getOrgId(), entity.getOrgName(), entity.getDelFlag(), entity.getType());
    }

    @Override
    public void deleteById(String id) {
        String sql = "update fxqh_attenuation_relationship_model set del_flag = '1'  where id = '" + id + "'";
        jdbcTemplate.update(sql);
    }

    @Override
    public Map<String, Object> page(ArModelPageParam param, int page, int size) {
        StringBuilder sql = new StringBuilder("select * from fxqh_attenuation_relationship_model where del_flag = '0'");
        if (PlatformObjectUtils.isNotEmpty(param.getModelName())) {
            sql.append(" and model_name like '%" + param.getModelName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(param.getProvince())) {
            if ("cd726776c7de41e4a41dcdb3d90b2806".equals(param.getProvince()) || "225ac763ab714524b87d95140a93a4a5".equals(param.getProvince()) || "8a3f7d3f78ad456f92f487a979091c7f".equals(param.getProvince()) || "afcbf07008a34c2e85917cfd34008033".equals(param.getProvince())) {
                //拿到北京上海天津重庆四省的省id
                String pid = areaService.getParentId(param.getProvince());
                param.setProvince(pid);
            }
            sql.append(" and (org_name = '系统默认' or province='").append(param.getProvince()).append("')");
        }
        if (!PlatformObjectUtils.isEmpty(param.getCity())) {
            sql.append(" and (position('").append(param.getCity()).append("' in city) > 0 ");
            sql.append(" or city='全部')");
        }
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(ModelPageVo.class)).size();
        StringBuilder limitSql = new StringBuilder(" limit " + size + " offset " + (page - 1) * size);
        StringBuilder orderSql = new StringBuilder(" order by is_default desc, create_time desc");
        sql.append(orderSql).append(limitSql);
        List<ModelPageVo> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(ModelPageVo.class));
        list.forEach(it -> {
            it.setProvince(sysAreaService.getAreaNameByAreaId(it.getProvince()));
            if (!it.getCity().equals("全部")) {
                it.setCity(sysAreaService.getAreaNameByAreaId(it.getCity()));
            }
        });
        HashMap<String, Object> resultMap = new HashMap();
        resultMap.put("total", total);
        resultMap.put("rows", list);
        return resultMap;
    }

    @Override
    public ArModelEntity getById(String id) {
        String sql = "select * from fxqh_attenuation_relationship_model where id = '" + id + "'";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(ArModelEntity.class));
    }

    @Override
    public void updateById(ArModelEntity entity) {
        jdbcTemplate.update("UPDATE  fxqh_attenuation_relationship_model  SET model_name=?,long_ratio1=?,long_ratio2=?,long_ratio3=?,long_ratio4=?,long_symbol=?,short_ratio1=?,short_ratio2=?,short_ratio3=?,short_ratio4=?,short_symbol=?,formula_ratio1=?,formula_ratio2=?,scale=?,is_default=?,update_user_id=?,update_time=?,org_id=?,org_name=?,type=?"
                        + " where id=?",
                entity.getModelName(), entity.getLongRatio1(), entity.getLongRatio2(), entity.getLongRatio3(), entity.getLongRatio4(), entity.getLongSymbol(), entity.getShortRatio1(), entity.getShortRatio2(), entity.getShortRatio3(), entity.getShortRatio4(), entity.getShortSymbol(), entity.getFormulaRatio1(), entity.getFormulaRatio2(), entity.getScale(), entity.getIsDefault(), entity.getUpdateUserId(), entity.getUpdateTime(), entity.getOrgId(), entity.getOrgName(), entity.getType(),
                entity.getId()
        );
    }


    @Override
    public void saveSettingInfluenceFlied(SettingInfluenceFliedEntity entity, Integer type) {
        try {
            if (type == 1 || type == 0) {
                String geomText = getGeomValidWkt(entity.getGeom());
                entity.setGeom(geomText);
            }
            String sql = "insert into fxqh_setting_seismic_influenceflied(id,earthquake_level,dz_intensity,long_x,short_y," +
                    "geom,data_source,assess_user_id,assess_user_dept,assess_time,direction,magnitude,longitude,latitude,source_earthquake_id,del_flag,assess_user_name,version_code,intensity_ch)" +
                    "values (:id,:earthquakeLevel,:dzIntensity,:longX,:shortY,ST_GeometryFromText(:geom,4490)," +
                    ":dataSource,:assessUserId,:assessUserDept,:assessTime,:direction,:magnitude,:longitude,:latitude,:sourceEarthquakeId,:delFlag,:assessUserName,:versionCode,:intensityCh)";
            SqlParameterSource source = new BeanPropertySqlParameterSource(entity);
            namedParameterJdbcTemplate.update(sql, source);
        } catch (Exception e) {
            throw new RuntimeException("保存失败", e);
        }
    }

    public String getGeomValidWkt(String geomText) {
        String valid = isGeomValid(geomText);
        if (valid.equals("t")) {//正常
            //
        } else if (valid.equals("f")) {//自相交
            //修复空间数据自相交，获取修复后的空间数据
            geomText = makeGeomValid(geomText);
        }
        //保持空间数据类型一致性
        if (geomText.indexOf("POLYGON") == 0) {//面转多面
            geomText = "MULTIPOLYGON(" + geomText.split("POLYGON")[1] + ")";
        }
        return geomText;
    }

    public String isGeomValid(String geomText) {
        String sql = "SELECT ST_IsValid(geom) FROM st_geomfromtext(?,4490) geom";
        return jdbcTemplate.queryForObject(sql, String.class, geomText);
    }

    public String makeGeomValid(String geomText) {
        String sql = "SELECT ST_AsText(ST_MakeValid(geom)) FROM st_geomfromtext(?,4490) geom";
        return jdbcTemplate.queryForObject(sql, String.class, geomText);
    }


    @Override
    public void saveSeismicPbe(SeismicPbeEntity entity) {
        try {
            String sql = "insert into fxqh_seismic_influencefly_pbe(id,influencefly_id,geom,longitude,latitude,earthquake_level,magnitude)" +
                    "values(:id,:influenceflyId,ST_GeometryFromText(:geom,4490),:longitude,:latitude,:earthquakeLevel,:magnitude)";
            SqlParameterSource source = new BeanPropertySqlParameterSource(entity);
            namedParameterJdbcTemplate.update(sql, source);
        } catch (Exception e) {
            throw new RuntimeException("保存失败", e);
        }
    }

    @Override
    public void saveSettingSeismicProcess(SettingSeismicProcessEntity entity) {
        jdbcTemplate.update("insert into fxqh_setting_seismic_process  (id,epicenter_intensity,long_length1,short_length1,long_length2,short_length2,long_length3,short_length3,long_length4,short_length4,long_length5,short_length5,create_user_id,create_user,del_flag,create_time,longitude,latitude,magnitude,direction,earthquake_impact_field_id ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )",
                entity.getId(), entity.getEpicenterIntensity(), entity.getLongLength1(), entity.getShortLength1(), entity.getLongLength2(), entity.getShortLength2(), entity.getLongLength3(), entity.getShortLength3(), entity.getLongLength4(), entity.getShortLength4(), entity.getLongLength5(), entity.getShortLength5(), entity.getCreateUserId(), entity.getCreateUser(), entity.getDelFlag(), entity.getCreateTime(), entity.getLongitude(), entity.getLatitude(), entity.getMagnitude(), entity.getDirection(), entity.getEarthquakeImpactFieldId());
    }

    @Override
    public Map<String, Object> getAll(int page, int size) {
        StringBuilder sql = new StringBuilder("select distinct(version_code), longitude,latitude,earthquake_level,direction,assess_user_name from fxqh_setting_seismic_influenceflied where del_flag = '0' order by version_code desc");
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(InfluencefliedVo.class)).size();
        StringBuilder limitSql = new StringBuilder(" limit " + size + " offset " + (page - 1) * size);
        sql.append(limitSql);
        List<InfluencefliedVo> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(InfluencefliedVo.class));
        HashMap<String, Object> resultMap = new HashMap();
        resultMap.put("total", total);
        resultMap.put("rows", list);
        return resultMap;
    }

    @Override
    public List<SettingInfluenceFliedEntity> getInfluencefliedById(String versionCode) {
        try {
            String sql = "select *,ST_AsText(geom) geom from fxqh_setting_seismic_influenceflied where version_code = '" + versionCode + "'";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SettingInfluenceFliedEntity.class));
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public SettingInfluenceFliedEntity findById(String id) {
        try {
            String sql = "select *,ST_AsText(geom) geom from fxqh_setting_seismic_influenceflied where id = '" + id + "'";
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(SettingInfluenceFliedEntity.class));
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public void deleteInfluencefliedById(String versionCode) {
        String sql = "update fxqh_setting_seismic_influenceflied set del_flag = '1' where version_code = '" + versionCode + "'";
        jdbcTemplate.update(sql);
    }

    @Override
    public List<String> getInfluencefliedId(String intensityVersion) {
        String sql = "select id from fxqh_setting_seismic_influenceflied where del_flag='0' and version_code='" + intensityVersion + "'";
        return jdbcTemplate.queryForList(sql, String.class);
    }

    @Override
    public String getInfluencefliedId(String intensityVersion, String intensity) {
        String sql = "select id from fxqh_setting_seismic_influenceflied where del_flag='0' and version_code='" + intensityVersion + "' and dz_intensity='" + intensity + "'";
        List<String> strings = jdbcTemplate.queryForList(sql, String.class);
        return strings.get(0);
    }

    @Override
    public List<SettingInfluenceFliedEntity> getInfluencefliedList(String intensityVersion) {
        String sql = "select * from fxqh_setting_seismic_influenceflied where del_flag='0' and version_code='" + intensityVersion + "'";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SettingInfluenceFliedEntity.class));
    }
}
